package com.ruoyi.web.controller.post;

import java.util.List;
import java.util.UUID;
import java.util.Date;

import com.github.pagehelper.PageHelper;
import com.ruoyi.post.domain.PostCommentInfo;
import com.ruoyi.post.domain.PostWithTagsRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.post.domain.PostBasicInfo;
import com.ruoyi.post.service.IPostBasicInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 帖子管理Controller
 *
 * @author 区嘉盛
 * @date 2025-06-10
 */
@RestController
@RequestMapping("/post/post")
@Tag(name = "【帖子管理】管理")
public class PostBasicInfoController extends BaseController {
    @Autowired
    private IPostBasicInfoService postBasicInfoService;

    /**
     * 查询帖子管理列表
     */
    @Operation(summary = "查询帖子管理列表")
    @GetMapping("/list")
    public TableDataInfo list(PostBasicInfo postBasicInfo) {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.selectPostBasicInfoList(postBasicInfo);
        return getDataTable(list);
    }

    /**
     * 导出帖子管理列表
     */
    @Operation(summary = "导出帖子管理列表")
    @PreAuthorize("@ss.hasPermi('post:post:export')")
    @Log(title = "帖子管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PostBasicInfo postBasicInfo) {
        List<PostBasicInfo> list = postBasicInfoService.selectPostBasicInfoList(postBasicInfo);
        ExcelUtil<PostBasicInfo> util = new ExcelUtil<PostBasicInfo>(PostBasicInfo.class);
        util.exportExcel(response, list, "帖子管理数据");
    }

    /**
     * 获取帖子管理详细信息
     */
    @Operation(summary = "获取帖子管理详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(postBasicInfoService.selectPostBasicInfoById(id));
    }

    /**
     * 给用户查询笔记、收藏、点赞的帖子
     *
     * @param type 1:笔记 2:收藏 3:点赞
     */
    @Operation(summary = "给用户查询笔记、收藏、点赞的帖子")
    @GetMapping(value = "/mine/{type}/{userId}")
    public TableDataInfo getPostForUser(@PathVariable("type") Long type, @PathVariable Long userId) {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.getPostForUser(type, userId);
        return getDataTable(list);
    }

    /**
     * 新增帖子管理
     */
    @Operation(summary = "新增帖子管理")
    @Log(title = "帖子管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PostBasicInfo postBasicInfo) {
        postBasicInfo.setPostCode(UUID.randomUUID().toString().replace("-", ""));
        return toAjax(postBasicInfoService.insertPostBasicInfo(postBasicInfo));
    }

    /**
     * 修改帖子管理
     */
    @Operation(summary = "修改帖子管理")
    @Log(title = "帖子管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PostBasicInfo postBasicInfo) {
        return toAjax(postBasicInfoService.updatePostBasicInfo(postBasicInfo));
    }

    /**
     * 删除帖子管理
     */
    @Operation(summary = "删除帖子管理")
    @Log(title = "帖子管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable(name = "id") Long id) {
        return toAjax(postBasicInfoService.deletePostBasicInfoById(id));
    }

    /**
     * 用户发布帖子
     */
    @Operation(summary = "用户发布帖子")
    @PostMapping("/publish")
    public AjaxResult publishPost(@RequestBody PostBasicInfo postBasicInfo) {
        postBasicInfo.setPostCode(UUID.randomUUID().toString().replace("-", ""));
        postBasicInfo.setAuthorUserId(getUserId());
        postBasicInfo.setCreatedBy(getUsername());
        try {
            String auditResult = postBasicInfoService.auditPostContent(postBasicInfo.getPostTitle(), postBasicInfo.getPostContent());
            if ("REJECT".equals(auditResult)) {
                postBasicInfo.setAiAuditStatus(2L);
                postBasicInfo.setAiAuditReason("内容包含不当信息，请修改后重新发布");
            } else {
                postBasicInfo.setAiAuditStatus(1L);
                postBasicInfo.setAiAuditReason(null);
            }
            postBasicInfo.setAiAuditTime(new Date());
        } catch (Exception e) {
            postBasicInfo.setAiAuditStatus(0L);
            postBasicInfo.setAiAuditReason("AI审核服务暂时不可用");
        }

        PostBasicInfo newPost = new PostBasicInfo();
        if (postBasicInfoService.publishPost(postBasicInfo, false) == 1) {
            newPost = postBasicInfoService.getNewPost(postBasicInfo.getPostCode());
        }

        return success(newPost.getId());
    }

    /**
     * 用户发布帖子并设置标签（事务性操作）
     */
    @Operation(summary = "用户发布帖子并设置标签")
    @PreAuthorize("@ss.hasRole('common')")
    @PostMapping("/publishWithTags")
    public AjaxResult publishPostWithTags(@RequestBody PostWithTagsRequest request) {
        PostBasicInfo postBasicInfo = request.getPostBasicInfo();
        List<Long> tagIds = request.getTagIds();

        postBasicInfo.setPostCode(UUID.randomUUID().toString().replace("-", ""));
        postBasicInfo.setAuthorUserId(getUserId());
        postBasicInfo.setCreatedBy(getUsername());

        try {
            // AI审核
            String auditResult = postBasicInfoService.auditPostContent(
                    postBasicInfo.getPostTitle(),
                    postBasicInfo.getPostContent()
            );

            if ("REJECT".equals(auditResult)) {
                postBasicInfo.setAiAuditStatus(2L);
                postBasicInfo.setAiAuditReason("内容包含不当信息，请修改后重新发布");
            } else {
                postBasicInfo.setAiAuditStatus(1L);
                postBasicInfo.setAiAuditReason(null);
            }
            postBasicInfo.setAiAuditTime(new Date());
        } catch (Exception e) {
            postBasicInfo.setAiAuditStatus(0L);
            postBasicInfo.setAiAuditReason("AI审核服务暂时不可用");
        }

        try {
            int result = postBasicInfoService.publishPostWithTags(postBasicInfo, tagIds);
            if (result > 0) {
                return success("发布成功");
            } else {
                return error("发布失败");
            }
        } catch (Exception e) {
            return error("发布失败：" + e.getMessage());
        }
    }

    /**
     * 保存帖子草稿
     */
    @Operation(summary = "保存帖子草稿")
    @PostMapping("/draft")
    public AjaxResult savePostDraft(@RequestBody PostBasicInfo postBasicInfo) {
        postBasicInfo.setPostCode(UUID.randomUUID().toString().replace("-", ""));
        postBasicInfo.setAuthorUserId(getUserId());
        postBasicInfo.setCreatedBy(getUsername());
        postBasicInfo.setAiAuditStatus(0L);
        return toAjax(postBasicInfoService.savePostDraft(postBasicInfo));
    }

    /**
     * 获取帖子草稿
     */
    @Operation(summary = "获取帖子草稿")
    @GetMapping("/getDraft")
    public AjaxResult getPostDraft() {
        return success(postBasicInfoService.getPostDraft(getUserId()));
    }

    /**
     * 用户删除自己的帖子
     */
    @Operation(summary = "用户删除自己的帖子")
    @DeleteMapping("/user/{postId}")
    public AjaxResult deleteUserPost(@PathVariable("postId") Long postId) {
        return toAjax(postBasicInfoService.deleteUserPost(postId, getUserId()));
    }

    /**
     * 根据圈子ID查询帖子列表
     */
    @Operation(summary = "根据圈子ID查询帖子列表")
    @GetMapping("/circle/byId/{circleId}")  // 修改路径以避免冲突
    public TableDataInfo getPostsByCircle(@PathVariable("circleId") Long circleId) {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.selectPostsByCircleId(circleId);
        return getDataTable(list);
    }

    /**
     * 查询用户的帖子列表
     */
    @Operation(summary = "查询用户的帖子列表")
    @GetMapping("/user")
    public TableDataInfo getUserPosts() {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.selectPostsByUserId(getUserId());
        return getDataTable(list);
    }

    /**
     * 帖子点赞/取消点赞
     */
    @Operation(summary = "帖子点赞/取消点赞")
    @PostMapping("/like/{postId}")
    public AjaxResult toggleLike(@PathVariable("postId") Long postId) {
        return toAjax(postBasicInfoService.togglePostLike(postId, getUserId()));
    }

    /**
     * 获取用户点赞的帖子ID列表
     */
    @Operation(summary = "获取用户点赞的帖子ID列表")
    @GetMapping("/userLiked")
    public AjaxResult getUserLikedPostIds() {
        List<Integer> list = postBasicInfoService.getUserLikedPostIds(getUserId());
        return success(list);
    }

    /**
     * 帖子收藏/取消收藏
     */
    @Operation(summary = "帖子收藏/取消收藏")
    @PostMapping("/favorite/{postId}")
    public AjaxResult toggleFavorite(@PathVariable("postId") Long postId) {
        return toAjax(postBasicInfoService.togglePostFavorite(postId, getUserId()));
    }

    /**
     * 获取用户收藏的帖子ID列表
     */
    @Operation(summary = "获取用户收藏的帖子ID列表")
    @GetMapping("/userFavorite")
    public AjaxResult getUserFavoritePostIds() {
        List<Integer> list = postBasicInfoService.getUserFavoritePostIds(getUserId());
        return success(list);
    }

    /**
     * 发表评论
     */
    @Operation(summary = "发表评论")
    @PostMapping("/comment")
    public AjaxResult addComment(@RequestBody PostCommentInfo postCommentInfo) {
        postCommentInfo.setCommentCode(UUID.randomUUID().toString().replace("-", ""));
        postCommentInfo.setCommenterUserId(getUserId());
        postCommentInfo.setCreateBy(getUsername());
        try {
            String auditResult = postBasicInfoService.auditCommentContent(postCommentInfo.getCommentContent());
            if ("REJECT".equals(auditResult)) {
                postCommentInfo.setAiAuditStatus(2L);
                postCommentInfo.setAiAuditReason("评论内容包含不当信息，请修改后重新发布");
            } else {
                postCommentInfo.setAiAuditStatus(1L);
                postCommentInfo.setAiAuditReason(null);
            }
            postCommentInfo.setAiAuditTime(new Date());
        } catch (Exception e) {
            postCommentInfo.setAiAuditStatus(0L);
            postCommentInfo.setAiAuditReason("AI审核服务暂时不可用");
        }
        return toAjax(postBasicInfoService.addComment(postCommentInfo, false));
    }

    /**
     * 保存评论草稿
     */
    @Operation(summary = "保存评论草稿")
    @PostMapping("/comment/draft")
    public AjaxResult saveCommentDraft(@RequestBody PostCommentInfo postCommentInfo) {
        postCommentInfo.setCommentCode(UUID.randomUUID().toString().replace("-", ""));
        postCommentInfo.setCommenterUserId(getUserId());
        postCommentInfo.setCreateBy(getUsername());
        postCommentInfo.setAiAuditStatus(0L);
        return toAjax(postBasicInfoService.addComment(postCommentInfo, true));
    }

    /**
     * 查询帖子评论列表
     */
    @Operation(summary = "查询帖子评论列表")
    @GetMapping("/comment/{postId}")
    public TableDataInfo getComments(@PathVariable("postId") Long postId,
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        startPage();
        List<PostCommentInfo> list = postBasicInfoService.selectCommentsByPostId(postId);
        return getDataTable(list);
    }

    /**
     * 用户删除自己的评论
     */
    @Operation(summary = "用户删除自己的评论")
    @DeleteMapping("/comment/{commentId}")
    public AjaxResult deleteUserComment(@PathVariable("commentId") Long commentId) {
        return toAjax(postBasicInfoService.deleteUserComment(commentId, getUserId()));
    }

    /**
     * 评论点赞/取消点赞
     */
    @Operation(summary = "评论点赞/取消点赞")
    @PostMapping("/comment/like/{commentId}")
    public AjaxResult toggleCommentLike(@PathVariable("commentId") Long commentId) {
        return toAjax(postBasicInfoService.toggleCommentLike(commentId, getUserId()));
    }

    /**
     * 根据帖子id获取用户点赞的评论ID列表
     */
    @Operation(summary = "获取用户点赞的评论ID列表")
    @GetMapping("/comment/userCommentLiked/{postId}")
    public AjaxResult getUserCommentLikedByPostId(@PathVariable("postId") Long postId) {
        List<Long> list = postBasicInfoService.getUserCommentLikedByPostId(postId, getUserId());
        return success(list);
    }

    /**
     * 查询用户收藏的帖子列表
     */
    @Operation(summary = "查询用户收藏的帖子列表")
    @GetMapping("/favorite")
    public TableDataInfo getFavoritePosts() {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.selectFavoritePostsByUserId(getUserId());
        return getDataTable(list);
    }

    /**
     * 根据帖子标题查询
     */
    @Operation(summary = "根据帖子标题查询")
    @GetMapping("/search/{postTitle}")
    public TableDataInfo getPostByPostTitle(@PathVariable String postTitle) {
        startPage();
        List<PostBasicInfo> list = postBasicInfoService.getPostByPostTitle(postTitle);
        return getDataTable(list);
    }
}
